package com.raowb.common.util;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 
* @Description:  spring工具类
* @author: raowb
* @date 2018年8月9日
 */
@Component("springContextUtil")
public class SpringBeanUtil implements ApplicationContextAware {

	private static ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		SpringBeanUtil.applicationContext = applicationContext;
	}

	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	@SuppressWarnings("unchecked")
	public static <T> T getBean(String beanName) {
		return (T) applicationContext.getBean(beanName);
	}

	public static <T> T getBean(Class<T> requiredType) {
		return applicationContext.getBean(requiredType);
	}

	/**
	 * 根据类型返回bean列表
	 * @param <T>
	 * 
	 * @param type
	 * @return
	 */
	public static <T> List<T> getBeansForType(Class<T> type) {
		String[] beanNameArr = applicationContext.getBeanNamesForType(type);
		List<T> beanList = new ArrayList<>();
		for (int i = 0; i < beanNameArr.length; i++) {
			beanList.add(getBean(beanNameArr[i]));
		}
		return beanList;
	}

	public static String[] getAllBeansName() {
		return applicationContext.getBeanDefinitionNames();
	}
}
